package es.udc.emarketapp.emarket.model.usersFacade.actions;

import es.udc.emarketapp.emarket.model.admin.dao.SQLAdminDAO;
import es.udc.emarketapp.emarket.model.admin.dao.SQLAdminDAOFactory;
import es.udc.emarketapp.emarket.model.admin.vo.AdminVO;
import es.udc.emarketapp.emarket.model.user.dao.SQLUserDAO;
import es.udc.emarketapp.emarket.model.user.dao.SQLUserDAOFactory;
import es.udc.emarketapp.emarket.model.user.vo.UserVO;
import es.udc.emarketapp.emarket.model.usersFacade.exceptions.IncorrectPasswordException;
import es.udc.emarketapp.emarket.model.usersFacade.util.PasswordEncrypter;
import es.udc.emarketapp.emarket.model.usersFacade.vo.LoginResultVO;
import es.udc.fbellas.j2ee.util.exceptions.InstanceNotFoundException;
import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.NonTransactionalPlainAction;
import java.sql.Connection;

public class LoginAction implements NonTransactionalPlainAction {

    public static final String ADMIN = "ADMIN";

    private String loginName;
    private String password;
    private boolean passwordIsEncrypted;
    private boolean isAdmin;

    public LoginAction(String loginName, String password,
            boolean passwordIsEncrypted, boolean isAdmin) {

        this.loginName = loginName;
        this.password = password;
        this.passwordIsEncrypted = passwordIsEncrypted;
        this.isAdmin = isAdmin;
    }

    /**
     *
     * @return a <code>LoginResultVO</code>
     */
    public Object execute(Connection connection)
            throws IncorrectPasswordException, InstanceNotFoundException,
            InternalErrorException {

        String storedPassword;
        String userName;
        String type;

        if (isAdmin) {

            SQLAdminDAO adminDAO = SQLAdminDAOFactory.getDAO();
            AdminVO adminVO = adminDAO.findById(connection, loginName);
            storedPassword = adminVO.getPass();
            userName = adminVO.getIdAdmin();
            type = ADMIN;

        } else {
            SQLUserDAO userDAO = SQLUserDAOFactory.getDAO();
            UserVO userVO = userDAO.findById(connection, loginName);
            storedPassword = userVO.getPass();
            userName = userVO.getIdUser();
            type = userVO.getTipoUsuario();
        }


        System.out.println("guardada" + storedPassword);
        System.out.println("recibida" + PasswordEncrypter.crypt(storedPassword));

     
         if (passwordIsEncrypted) {
                if (!password.equals(storedPassword)) {
                    throw new IncorrectPasswordException(loginName);
                }
            } else {
                if (!PasswordEncrypter.isClearPasswordCorrect(password,
                        storedPassword)) {
                    throw new IncorrectPasswordException(loginName);
                }
            }
       

        return new LoginResultVO(userName, storedPassword, type);

    }
}
